import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'dart:math';
import '../../function/states/encyclopedia_state.dart';
import '../../function/states/post_state.dart';
import '../../function/states/user_state.dart';
import '../../function/states/follow_state.dart';
import '../../function/widgets/login_dialog.dart';
import '../../function/widgets/animated_tap_widget.dart';
import '../../function/widgets/toast_widget.dart';
import '../../function/widgets/report_dialog.dart';
import '../../function/routes/app_route_manager.dart';

/// 首页
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
    // 监听登录状态变化
    UserState.isLoggedInBeacon.subscribe((isLoggedIn) {
      if (mounted) {
        setState(() {});
      }
    });
    UserState.currentUserBeacon.subscribe((currentUser) {
      if (mounted) {
        setState(() {});
      }
    });
    // 监听百科全书分类状态变化
    EncyclopediaState.currentCategoryBeacon.subscribe((category) {
      if (mounted) {
        setState(() {});
      }
    });
    // 监听关注状态变化
    FollowState.userFollowsMapBeacon.subscribe((followsMap) {
      if (mounted) {
        setState(() {});
      }
    });
    // 监听点赞状态变化
    PostState.userFavoritePostsMapBeacon.subscribe((favoritesMap) {
      if (mounted) {
        setState(() {});
      }
    });

    // 监听动态列表变化
    PostState.postListBeacon.subscribe((postList) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  /// 格式化时间显示
  String _formatTimeAgo(DateTime publishTime) {
    final now = DateTime.now();
    final difference = now.difference(publishTime);

    if (difference.inMinutes < 1) {
      return 'Just now';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes} Min Ago';
    } else if (difference.inHours < 24) {
      return '${difference.inHours} Hour${difference.inHours > 1 ? 's' : ''} Ago';
    } else if (difference.inDays < 7) {
      return '${difference.inDays} Day${difference.inDays > 1 ? 's' : ''} Ago';
    } else if (difference.inDays < 30) {
      final weeks = (difference.inDays / 7).floor();
      return '$weeks Week${weeks > 1 ? 's' : ''} Ago';
    } else if (difference.inDays < 365) {
      final months = (difference.inDays / 30).floor();
      return '$months Month${months > 1 ? 's' : ''} Ago';
    } else {
      final years = (difference.inDays / 365).floor();
      return '$years Year${years > 1 ? 's' : ''} Ago';
    }
  }

  void _handleUserAvatarTap(String userId) {
    if (userId.isEmpty) return;

    final currentUser = UserState.getCurrentUserInfo();
    if (currentUser != null && currentUser.userId == userId) {
      // 如果是当前用户，跳转到自己的用户中心
      AppRouteManager.navigateToUserCenter();
    } else {
      // 如果是其他用户，跳转到其他用户主页
      AppRouteManager.navigateToOtherUserCenter(userId);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 固定的应用头部
              _buildAppHeader(context),

              // 可滚动的内容区域
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 20.h),

                      // 主标题
                      _buildMainTitle(),

                      SizedBox(height: 30.h),

                      // 百科导航部分
                      _buildEncyclopediaSection(context),

                      SizedBox(height: 20.h),

                      // 百科卡片
                      _buildEncyclopediaCards(context),

                      SizedBox(height: 20.h),

                      // 热门动态部分
                      _buildHotNewsSection(context),

                      SizedBox(height: 130.h),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建应用头部
  Widget _buildAppHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 左侧：应用名称和星星图标
          Row(
            children: [
              Image.asset('assets/images/star.png', width: 20.w, height: 20.w),
              SizedBox(width: 8.w),
              Text('Mesh')
                  .fontSize(24.sp)
                  .textColor(Colors.white)
                  .fontWeight(FontWeight.w700),
            ],
          ),

          // 右侧：通知铃铛和用户信息盒子
          Row(
            children: [
              AnimatedTapWidget(
                onTap: () {
                  final isLoggedIn = UserState.checkLoginStatus();
                  if (!isLoggedIn) {
                    LoginDialog.show(
                      context,
                      title: 'Login Required',
                      message: 'Please login to view notifications',
                    );
                    return;
                  }
                  // 跳转到消息通知页面
                  AppRouteManager.navigateToMessageCenter();
                },
                child: Container(
                  width: 30.w,
                  height: 30.w,
                  decoration: BoxDecoration(
                    color: const Color(0x33FF8A3C),
                    shape: BoxShape.circle,
                  ),
                  child: Padding(
                    padding: EdgeInsets.all(6.w),
                    child: Image.asset(
                      'assets/images/notification.png',
                      width: 18.w,
                      height: 18.w,
                    ),
                  ),
                ),
              ),
              SizedBox(width: 12.w),
              _buildUserInfoBox(context),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建用户信息盒子
  Widget _buildUserInfoBox(BuildContext context) {
    return AnimatedTapWidget(
      onTap: () {
        final isLoggedIn = UserState.checkLoginStatus();
        if (!isLoggedIn) {
          LoginDialog.show(
            context,
            title: 'Login Required',
            message: 'Please login to view your profile',
          );
          return;
        }
        // 跳转到用户中心页面
        AppRouteManager.navigateToUserCenter();
      },
      child: Container(
        height: 30.w,
        padding: EdgeInsets.symmetric(horizontal: 12.w),
        decoration: BoxDecoration(
          color: const Color(0x33FF8A3C),
          borderRadius: BorderRadius.circular(15.r),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 用户头像
            _buildUserAvatar(),
            SizedBox(width: 8.w),
            // 用户名
            Builder(
              builder: (context) {
                final isLoggedIn = UserState.checkLoginStatus();
                final currentUser = UserState.getCurrentUserInfo();
                return Text(
                      isLoggedIn && currentUser != null
                          ? currentUser.userName
                          : 'Guest',
                    )
                    .fontSize(16.sp)
                    .textColor(const Color(0xFFFF8A3C))
                    .fontFamily(
                      GoogleFonts.roboto(
                        fontWeight: FontWeight.w400,
                      ).fontFamily,
                    )
                    .fontWeight(FontWeight.w500);
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 构建用户头像
  Widget _buildUserAvatar() {
    return Builder(
      builder: (context) {
        final isLoggedIn = UserState.checkLoginStatus();
        final currentUser = UserState.getCurrentUserInfo();

        if (isLoggedIn && currentUser != null) {
          // 已登录：显示用户头像
          return Container(
            width: 20.w,
            height: 20.w,
            decoration: BoxDecoration(shape: BoxShape.circle),
            child: ClipOval(
              child: Image.asset(currentUser.avatar, fit: BoxFit.cover),
            ),
          );
        } else {
          // 未登录：显示默认圆形图标
          return Container(
            width: 20.w,
            height: 20.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.white.withOpacity(0.2),
              border: Border.all(color: const Color(0xFFFF8A3C), width: 1.w),
            ),
            child: Icon(
              Icons.person,
              color: const Color(0xFFFF8A3C),
              size: 12.w,
            ),
          );
        }
      },
    );
  }

  /// 构建主标题
  Widget _buildMainTitle() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Container(
        constraints: BoxConstraints(maxWidth: 258.w),
        child: Text(
              'Lemurs, Baobabs, And Buddies: Your \nMadagascar Story Starts\nWith A Chat.',
            )
            .fontSize(24.sp)
            .textColor(const Color(0xFFFF8A3C))
            .fontFamily(
              GoogleFonts.rokkitt(fontWeight: FontWeight.w400).fontFamily,
            )
            .textAlignment(TextAlign.left),
      ),
    );
  }

  /// 构建百科导航部分
  Widget _buildEncyclopediaSection(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 左侧：百科图片和标题
          Row(
            children: [
              SizedBox(
                height: 42.h,
                child: AspectRatio(
                  aspectRatio: 62 / 42,
                  child: Image.asset(
                    'assets/images/encyclopedia.png',
                    fit: BoxFit.contain,
                  ),
                ),
              ),
              SizedBox(width: 8.w),
              Text('Encyclopedia')
                  .fontSize(12.sp)
                  .textColor(Colors.white)
                  .fontFamily(
                    GoogleFonts.quicksand(
                      fontWeight: FontWeight.w700,
                    ).fontFamily,
                  ),
            ],
          ),

          // 中间：分类按钮
          Row(
            children: [
              _buildCategoryButton(
                'Animal',
                EncyclopediaState.getCurrentCategory() == 'animal',
                () => EncyclopediaState.setCurrentCategory('animal'),
              ),
              SizedBox(width: 12.w),
              _buildCategoryButton(
                'Plant',
                EncyclopediaState.getCurrentCategory() == 'plant',
                () => EncyclopediaState.setCurrentCategory('plant'),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建分类按钮
  Widget _buildCategoryButton(String text, bool isActive, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 5.h),
        decoration: BoxDecoration(
          color:
              isActive
                  ? const Color(0xFFFF8A3C).withOpacity(0.2)
                  : Colors.transparent,
          borderRadius: BorderRadius.circular(15.r),
          border: Border.all(
            color: isActive ? const Color(0xFFFF8A3C) : Colors.white,
            width: isActive ? 1.0.w : 0.4.w,
          ),
        ),
        child: AnimatedDefaultTextStyle(
          duration: const Duration(milliseconds: 300),
          style: TextStyle(
            fontSize: 14.sp,
            color: isActive ? const Color(0xFFFF8A3C) : Colors.white,
            fontWeight: FontWeight.w600,
            fontFamily:
                GoogleFonts.quicksand(fontWeight: FontWeight.w600).fontFamily,
          ),
          child: Text(text),
        ),
      ),
    );
  }

  /// 构建百科卡片
  Widget _buildEncyclopediaCards(BuildContext context) {
    final currentCategory = EncyclopediaState.getCurrentCategory();
    final encyclopediaList =
        currentCategory == 'animal'
            ? EncyclopediaState.getAnimalEncyclopedia()
            : EncyclopediaState.getPlantEncyclopedia();
    if (encyclopediaList.length < 2) return SizedBox.shrink();

    // 随机选择两条百科数据
    final random = Random();
    final shuffledList = List.from(encyclopediaList)..shuffle(random);
    final firstEncyclopedia = shuffledList[0];
    final secondEncyclopedia = shuffledList[1];

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: AnimatedSwitcher(
        duration: const Duration(milliseconds: 600),
        transitionBuilder: (Widget child, Animation<double> animation) {
          return SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(0.0, 0.4),
              end: Offset.zero,
            ).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeOutCubic),
            ),
            child: FadeTransition(opacity: animation, child: child),
          );
        },
        child: Row(
          key: ValueKey(currentCategory),
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 左侧大图
            Expanded(
              flex: 192,
              child: _buildEncyclopediaCard(firstEncyclopedia, 192, 218),
            ),
            SizedBox(width: 12.w),
            // 右侧列
            Expanded(
              flex: 141,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  // See All 按钮
                  AnimatedTapWidget(
                    onTap: () {
                      // 跳转到百科列表页面
                      AppRouteManager.navigateToEncyclopediaList(
                        currentCategory,
                      );
                    },
                    child: Column(
                      children: [
                        Image.asset(
                          'assets/images/arrow.png',
                          width: 22.w,
                          height: 22.w,
                        ),
                        Text('See All')
                            .fontSize(12.sp)
                            .textColor(Colors.white)
                            .fontFamily(
                              GoogleFonts.quicksand(
                                fontWeight: FontWeight.w600,
                              ).fontFamily,
                            )
                            .fontWeight(FontWeight.w400)
                            .textAlignment(TextAlign.center),
                      ],
                    ),
                  ),
                  SizedBox(height: 12.h),
                  // 第二张图片
                  _buildEncyclopediaCard(secondEncyclopedia, 141, 165),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建单个百科卡片
  Widget _buildEncyclopediaCard(
    dynamic encyclopedia,
    int widthRatio,
    int heightRatio,
  ) {
    return GestureDetector(
      onTap: () {
        // 跳转到百科详情页面
        AppRouteManager.navigateToEncyclopediaDetail(
          encyclopedia.encyclopediaId,
        );
      },
      child: AspectRatio(
        aspectRatio: widthRatio / heightRatio,
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 8,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(16.r),
            child: Stack(
              children: [
                // 背景图片
                Image.asset(
                  encyclopedia.imageUrl,
                  width: double.infinity,
                  height: double.infinity,
                  fit: BoxFit.cover,
                ),

                // 渐变遮罩
                Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colors.black.withOpacity(0),
                        Colors.black.withOpacity(0.5),
                      ],
                    ),
                  ),
                ),

                // 内容
                Padding(
                  padding: EdgeInsets.all(12.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 标题
                      Expanded(
                        child: Text(encyclopedia.name)
                            .fontSize(16.sp)
                            .textColor(Colors.white)
                            .fontWeight(FontWeight.bold)
                            .textAlignment(TextAlign.left),
                      ),

                      // 查看按钮
                      Align(
                        alignment: Alignment.bottomRight,
                        child: Container(
                          width: 37.w,
                          height: 37.h,
                          decoration: BoxDecoration(
                            color: Color(0x33FF8A3C),
                            shape: BoxShape.circle,
                            border: Border.all(
                              color: Colors.white,
                              width: 0.1.w,
                            ),
                          ),
                          child: Center(
                            child: Text('View')
                                .fontSize(11.sp)
                                .textColor(Colors.white)
                                .fontWeight(FontWeight.w700),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建热门动态部分
  Widget _buildHotNewsSection(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text('Hot News')
              .fontSize(24.sp)
              .textColor(Colors.white)
              .fontFamily(
                GoogleFonts.rokkitt(fontWeight: FontWeight.w400).fontFamily,
              ),

          SizedBox(height: 16.h),

          // 动态卡片列表
          ...PostState.getAllPosts().map(
            (post) => _buildPostCard(context, post),
          ),
        ],
      ),
    );
  }

  /// 构建动态卡片
  Widget _buildPostCard(BuildContext context, dynamic post) {
    final userInfo = PostState.getUserInfo(post.userId);
    final userName = userInfo?['userName'] ?? 'Guest';
    final userAvatar =
        userInfo?['userAvatar'] ?? 'assets/images/avatars/default.jpg';

    // 获取当前登录用户信息
    final currentUser = UserState.getCurrentUserInfo();
    final isLoggedIn = UserState.checkLoginStatus();
    final currentUserId = currentUser?.userId ?? '';

    // 检查是否已关注该用户
    final isFollowing = FollowState.isFollowing(currentUserId, post.userId);

    // 检查是否已收藏该动态
    final isFavorited = PostState.isPostFavorited(currentUserId, post.postId);

    return GestureDetector(
      onTap: () => AppRouteManager.navigateToPostDetail(post.postId),
      child: Container(
        margin: EdgeInsets.only(bottom: 20.h),
        child: AspectRatio(
          aspectRatio: 343 / 274,
          child: Container(
            decoration: BoxDecoration(
              color: const Color(0xFF663507),
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 用户信息头部
                  Row(
                    children: [
                      // 用户头像
                      GestureDetector(
                        onTap: () => _handleUserAvatarTap(post.userId),
                        child: ClipOval(
                          child: Image.asset(
                            userAvatar,
                            width: 40.w,
                            height: 40.w,
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      SizedBox(width: 12.w),
                      // 用户名和时间
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(userName)
                                .fontSize(16.sp)
                                .textColor(Colors.white)
                                .fontWeight(FontWeight.w800)
                                .fontFamily(
                                  GoogleFonts.quicksand(
                                    fontWeight: FontWeight.w800,
                                  ).fontFamily,
                                ),
                            Text(_formatTimeAgo(post.publishTime))
                                .fontSize(12.sp)
                                .textColor(Colors.white)
                                .fontFamily(
                                  GoogleFonts.quicksand(
                                    fontWeight: FontWeight.w600,
                                  ).fontFamily,
                                ),
                          ],
                        ),
                      ),
                      // Follow按钮
                      GestureDetector(
                        onTap: () {
                          if (!isLoggedIn) {
                            LoginDialog.show(
                              context,
                              title: 'Login Required',
                              message: 'Please login to follow users',
                            );
                            return;
                          }

                          // 检查是否是自己
                          if (currentUserId == post.userId) {
                            ToastWidget.showWarning(
                              'You cannot follow yourself',
                            );
                            return;
                          }

                          // 切换关注状态
                          FollowState.toggleFollow(currentUserId, post.userId);
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 12.w,
                            vertical: 6.h,
                          ),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(32.r),
                          ),
                          child: AnimatedContainer(
                            duration: Duration(milliseconds: 300),
                            curve: Curves.easeInOut,
                            padding: EdgeInsets.symmetric(
                              horizontal: 12.w,
                              vertical: 6.h,
                            ),
                            decoration: BoxDecoration(
                              color:
                                  isFollowing
                                      ? const Color(0xFF854914)
                                      : Colors.white,
                              borderRadius: BorderRadius.circular(32.r),
                              border: Border.all(
                                color:
                                    isFollowing
                                        ? const Color(0xFF854914)
                                        : Colors.white,
                                width: 1.w,
                              ),
                            ),
                            child: AnimatedSwitcher(
                              duration: Duration(milliseconds: 200),
                              transitionBuilder: (
                                Widget child,
                                Animation<double> animation,
                              ) {
                                return FadeTransition(
                                  opacity: animation,
                                  child: ScaleTransition(
                                    scale: animation,
                                    child: child,
                                  ),
                                );
                              },
                              child: Row(
                                key: ValueKey(isFollowing),
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  AnimatedSwitcher(
                                    duration: Duration(milliseconds: 200),
                                    child: Image.asset(
                                      key: ValueKey(isFollowing),
                                      isFollowing
                                          ? 'assets/images/unfollow.png'
                                          : 'assets/images/follow.png',
                                      width: 14.w,
                                      height: 14.w,
                                      color:
                                          isFollowing
                                              ? Colors.white
                                              : const Color(0xFFFF8A3C),
                                    ),
                                  ),
                                  SizedBox(width: 4.w),
                                  AnimatedDefaultTextStyle(
                                    duration: Duration(milliseconds: 200),
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color:
                                          isFollowing
                                              ? Colors.white
                                              : const Color(0xFFFF8A3C),
                                      fontFamily:
                                          GoogleFonts.quicksand(
                                            fontWeight: FontWeight.w600,
                                          ).fontFamily,
                                      fontWeight: FontWeight.w600,
                                    ),
                                    child: Text(
                                      isFollowing ? 'Unfollow' : 'Follow',
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),

                  SizedBox(height: 12.h),

                  // 动态内容
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 文字内容
                        Text(
                              post.content.length > 100
                                  ? '${post.content.substring(0, 100)}...'
                                  : post.content,
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            )
                            .fontSize(12.sp)
                            .fontFamily(
                              GoogleFonts.quicksand(
                                fontWeight: FontWeight.w700,
                              ).fontFamily,
                            )
                            .textColor(Colors.white)
                            .textAlignment(TextAlign.left),

                        SizedBox(height: 8.h),

                        // 媒体画廊（图片和视频缩略图）
                        if (post.mediaUrls.isNotEmpty)
                          Expanded(
                            child: Container(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10.r),
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(10.r),
                                child: Row(
                                  children: [
                                    // 固定显示3个位置
                                    for (int i = 0; i < 3; i++) ...[
                                      Expanded(
                                        child: Container(
                                          margin: EdgeInsets.only(right: 4.w),
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(
                                              8.r,
                                            ),
                                            color:
                                                i < post.mediaUrls.length
                                                    ? null
                                                    : Colors.transparent,
                                            image:
                                                i < post.mediaUrls.length
                                                    ? DecorationImage(
                                                      image: AssetImage(
                                                        post.isVideoAtIndex(
                                                                  i,
                                                                ) &&
                                                                post.getVideoThumbnailAtIndex(
                                                                      i,
                                                                    ) !=
                                                                    null
                                                            ? post
                                                                .getVideoThumbnailAtIndex(
                                                                  i,
                                                                )!
                                                            : post.mediaUrls[i],
                                                      ),
                                                      fit: BoxFit.cover,
                                                    )
                                                    : null,
                                          ),
                                          child:
                                              i < post.mediaUrls.length &&
                                                      post.isVideoAtIndex(i)
                                                  ? Stack(
                                                    children: [
                                                      Center(
                                                        child: Image.asset(
                                                          'assets/images/play.png',
                                                          width: 24.w,
                                                          height: 24.w,
                                                        ),
                                                      ),
                                                    ],
                                                  )
                                                  : null,
                                        ),
                                      ),
                                    ],
                                  ],
                                ),
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),

                  SizedBox(height: 8.h),

                  // 底部操作栏
                  Container(
                    width: double.infinity,
                    height: 44.h,
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    decoration: ShapeDecoration(
                      color: const Color(0xFF854914),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(14.r),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // 点赞和评论
                        Row(
                          children: [
                            AnimatedTapWidget(
                              onTap: () {
                                if (!isLoggedIn) {
                                  LoginDialog.show(
                                    context,
                                    title: 'Login Required',
                                    message: 'Please login to favorite posts',
                                  );
                                  return;
                                }

                                // 切换收藏状态
                                PostState.togglePostFavorite(
                                  currentUserId,
                                  post.postId,
                                );
                              },
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  AnimatedSwitcher(
                                    duration: Duration(milliseconds: 200),
                                    transitionBuilder: (
                                      Widget child,
                                      Animation<double> animation,
                                    ) {
                                      return ScaleTransition(
                                        scale: animation,
                                        child: FadeTransition(
                                          opacity: animation,
                                          child: child,
                                        ),
                                      );
                                    },
                                    child: Image.asset(
                                      key: ValueKey(isFavorited),
                                      isFavorited
                                          ? 'assets/images/like-fill.png'
                                          : 'assets/images/like.png',
                                      width: 20.w,
                                      height: 20.w,
                                    ),
                                  ),
                                  SizedBox(width: 4.w),
                                  AnimatedDefaultTextStyle(
                                    duration: Duration(milliseconds: 200),
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: Colors.white,
                                      fontFamily:
                                          GoogleFonts.quicksand(
                                            fontWeight: FontWeight.w600,
                                          ).fontFamily,
                                      fontWeight: FontWeight.w600,
                                    ),
                                    child: Text('${post.favoriteCount}'),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(width: 16.w),
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Image.asset(
                                  'assets/images/comment.png',
                                  width: 20.w,
                                  height: 20.w,
                                ),
                                SizedBox(width: 4.w),
                                Text('${post.commentCount}')
                                    .fontSize(14.sp)
                                    .textColor(Colors.white)
                                    .fontFamily(
                                      GoogleFonts.quicksand(
                                        fontWeight: FontWeight.w600,
                                      ).fontFamily,
                                    ),
                              ],
                            ),
                          ],
                        ),
                        // 举报按钮
                        AnimatedTapWidget(
                          onTap: () {
                            ReportDialog.show(
                              context,
                              title: 'Report Post',
                              content:
                                  'Please select a reason for reporting this post',
                              onReportSuccess: () {
                                // 举报成功后删除动态
                                PostState.removePost(post.postId);
                                ToastWidget.showSuccess(
                                  'You won\'t see this post again.',
                                );
                              },
                            );
                          },
                          child: Image.asset(
                            'assets/images/report.png',
                            width: 20.w,
                            height: 20.w,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
